package com.johnny.xia.util.SerializableUtil;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @ClassName RSAEncryptUtil
 * @Author johnny xia
 * @mailto johnny.xia@qq.com
 * @Date 2020/9/3 3:41 下午
 * @Description RSA 对称加密
 **/
@Slf4j
public class RSAEncryptUtil {

    public static final String RSA_KEY_NAME = "RSA";

    private RSAEncryptUtil(){
        throw new IllegalStateException("Utility class");
    }
    /**
     * RSA公钥加密
     *
     * @param str
     *            加密字符串
     * @param publicKey
     *            公钥
     * @return 密文
     * @throws Exception
     *             加密过程中的异常信息
     */
    public static String encrypt( String str, String publicKey )  throws  NoSuchAlgorithmException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException, InvalidKeySpecException{
        //base64编码的公钥
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance(RSA_KEY_NAME).generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance(RSA_KEY_NAME);
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        return Base64.encodeBase64String(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)));
    }

    /**
     * RSA私钥解密
     *
     * @param str
     *            加密字符串
     * @param privateKey
     *            私钥
     * @return 铭文
     * @throws Exception
     *             解密过程中的异常信息
     */
    public static String decrypt(String str, String privateKey) throws  NoSuchAlgorithmException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException, InvalidKeySpecException {
        //64位解码加密后的字符串
        byte[] inputByte = Base64.decodeBase64(str.getBytes(StandardCharsets.UTF_8));
        //base64编码的私钥
        byte[] decoded = Base64.decodeBase64(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance(RSA_KEY_NAME).generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance(RSA_KEY_NAME);
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        return  new String(cipher.doFinal(inputByte));
    }

    public static void main(String[] args){
        String str = "clientId=opsportal&timestamp="+(System.currentTimeMillis()/1000);
        String pkey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArymZO4P2sXBUhydonfJzyrYaKiOYjr4rf66mmreVRhE7ahz1F6emlXrvlOBQhado94jWaSaIyih5EGSXgpCiDgqnYABkXRNkA8GcPx2p5XBJeH+/oazwOzSZHW8++efS24Vm91P1DAEcTV8x9OM+AadfSB69U8fOrnlAJhQZl5spEuaVhlzTGZYIrYdS7HJVUtOvoed/qXwwxORbUZC26fHYa/dhgKQEvPLZKsyIz0SUMOX7IP9koXWZUxiBePAhzT2PeprFxFpGKXNMi/wXzq8Fm1rcBMQE/Ggp5r3y+vCG9lm7taO7cn1NgiL/qATme15zk5NCmSPYIpYU+f8vnQIDAQAB";
        try {
            String tmp = RSAEncryptUtil.encrypt(str,pkey);
            System.out.println(tmp);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
    }
}
